import { login, register, getInfo, getPerm } from '@/api/user'
import router from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    userPerm: {}, // 当前用户的页面权限
    userPoint: {} // 当前用户的按钮权限
  },
  mutations: {
    setTokenMutations(state, token) {
      state.token = token
    },
    async removeTokenMutations(state, token) {
      state.token = null
      await removeToken()
    },
    setUserInfoMutations(state, data) {
      state.userInfo = data
    },
    setUserPermMutations(state, perm) {
      state.userPerm = perm
    },
    setUserPointmMutations(state, point) {
      state.userPoint = point
    }
  },
  actions: {
    // 登录
    async vuexLogin(store, data) {
      const res = await login(data)
      // 本地永久存储
      setToken(res.data.jwt)
      // 保存在vuex的user模块内的state
      store.commit('setTokenMutations', res.data.jwt)
    },
    // 登出
    vuexLogout(store) {
      store.commit('removeTokenMutations')
      router.go(0)
    },
    // 注册
    async vuxRegister(store, data) {
      await register(data)
    },
    // 获取当前用户信息
    async vuexGetInfo(store, data) {
      const res = await getInfo()
      const perm = await getPerm()
      // console.log('getInfo', 39, res)
      store.commit('setUserInfoMutations', res.data)
      store.commit('setUserPermMutations', perm.data.menus)
      store.commit('setUserPointmMutations', perm.data.points)
      console.log('user/modules/store-57-当前用户页面权限', perm.data.menus)
      console.log('user/modules/store-58-当前用户按钮权限', perm.data.points)
    }
  }
}

